package com.wangshouyu.mp.micro.token;

import com.google.gson.Gson;
import com.wangshouyu.mp.micro.base.constant.UrlConstant;
import com.wangshouyu.mp.micro.base.utils.HttpUtils;

import java.text.MessageFormat;

/**
 * @author 王守钰
 * @date 2020年08月16日 00:58
 * @description: 微信小程序accessToken 工具类
 */
public class AccessTokenUtils {

    private AccessTokenUtils(){}

    private static final Gson GSON = new Gson();

    /**
     * 获取AccessToken
     * @param appId 公众号ID
     * @param secret 公众秘钥
     * @return
     */
    public static AccessToken accessToken(String appId, String secret){
        synchronized (appId){
            String requestUrl = MessageFormat.format(UrlConstant.ACCESS_TOKEN_URL, appId,secret);
            try {
                String result = HttpUtils.getData(requestUrl);
                return GSON.fromJson(result, AccessToken.class);
            } catch (Exception e) {
                throw new AccessTokenException(e);
            }
        }
    }
}
